package com.rams.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import Decoder.BASE64Encoder;

import com.rams.dao.LoginDao;
import com.rams.dao.UserDao;
import com.rams.domain.vo.User;
import com.rams.service.LoginService;
import com.rams.service.vo.DisplayVO;

@Service
public class LoginServiceImpl implements LoginService{

	@Autowired
	LoginDao loginDao;
	
	@Autowired
	UserDao userDao;
	
	private Random random = new SecureRandom();
	
	@Override
	public DisplayVO validateLogin(User user) {
		System.out.println("MongoConnectionServiceImpl.getUserData()");
		DisplayVO displayVO = new DisplayVO();
	 
		// find the saved user again.
		User savedUser = loginDao.getUser(user.getUsername());
		System.out.println("2. find - savedUser : " + savedUser);
		if(null != savedUser){
			 String hashedAndSalted = savedUser.getPassword();
			 String salt = hashedAndSalted.split(",")[1];
	
		        if (!hashedAndSalted.equals(makePasswordHash(user.getPassword(), salt))) {
		            System.out.println("Submitted password is not a match");
		            displayVO.setStatus(false);
		        } else {
		        	System.out.println("Authenticated !!!!");
		        	displayVO.setStatus(true);
		        	displayVO.setUserCircles(userDao.getUserCircles(savedUser));
				    displayVO.setUser(savedUser);
		        }
		        

		       
		}
		
	        return displayVO;
		
	 
		/*// update password
		mongoOperation.updateFirst(searchUserQuery, 
	                         Update.update("password", "new password"),User.class);
	 
		// find the updated user object
		User updatedUser = mongoOperation.findOne(searchUserQuery, User.class);
	 
		System.out.println("3. updatedUser : " + updatedUser);
	 
		// delete
		mongoOperation.remove(searchUserQuery, User.class);
	 
		// List, it should be empty now.
		List<User> listUser = mongoOperation.findAll(User.class);
		System.out.println("4. Number of user = " + listUser.size());*/
	
	}

	@Override
	public boolean createNewUser(User user) {
		
		String hashedPassword = makePasswordHash(user.getPassword(), Integer.toString(random.nextInt()));
		user.setPassword(hashedPassword);
		
		return loginDao.createNewUser(user);
		
		
	}
	
	private String makePasswordHash(String password, String salt) {
        try {
            String saltedAndHashed = password + "," + salt;
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(saltedAndHashed.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes();
            return encoder.encode(hashedBytes) + "," + salt;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 is not available", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 unavailable?  Not a chance", e);
        }
    }

	

}
